//
//  KImageView.m
//  NeiHan
//
//  Created by 柯平 on 2017/3/11.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KImageView.h"

@interface KImageView ()
@property(nonatomic,copy)NSURL* imageURL;
@property (nonatomic, weak) UIActivityIndicatorView *indicator;
@property (nonatomic, weak) CAShapeLayer *progressLayer;

@end

@implementation KImageView
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.showIndicator = NO;
        self.showProgress = YES;
        self.showTip = YES;
    }
    return self;
}

-(instancetype)init{
    self = [super init];
    if (self) {
        self.showIndicator = NO;
        self.showProgress = YES;
        self.showTip = YES;
    }
    return self;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    
//    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.mas_equalTo(self);
//    }];
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self);
    }];
    [self.label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.imageView);
    }];
    [self.indicator mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.mas_centerX);
        make.centerY.mas_equalTo(self.mas_centerY);
    }];
}

-(UILabel *)label{
    if (!_label) {
        UILabel* lb = [[UILabel alloc]initWithFrame:self.bounds];
        lb.textAlignment = NSTextAlignmentCenter;
        lb.textColor = [UIColor colorWithWhite:0.7 alpha:1.0];
        lb.text = @"加载失败，点击重新加载！";
        [lb setAdjustsFontSizeToFitWidth:YES];
        lb.hidden = YES;
        lb.userInteractionEnabled = YES;
       __weak typeof(self) _self = self;
        UITapGestureRecognizer *g = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id sender) {
            [_self setImageURL:_self.imageURL];
            
        }];
        [_label addGestureRecognizer:g];
        [self addSubview:lb];
        _label = lb;
    }
    return _label;
}

-(CAShapeLayer *)progressLayer{
    if (!_progressLayer) {
        CGFloat lineHeight = 4;
        CAShapeLayer* layer = [CAShapeLayer layer];
        layer.size = CGSizeMake(self.imageView.width, lineHeight);
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake(0, layer.height / 2)];
        [path addLineToPoint:CGPointMake(self.imageView.width, layer.height / 2)];
        _progressLayer.lineWidth = lineHeight;
        layer.path = path.CGPath;
        layer.strokeColor = [UIColor colorWithRed:0.000 green:0.640 blue:1.000 alpha:0.720].CGColor;
        layer.lineCap = kCALineCapButt;
        layer.strokeStart = 0;
        layer.strokeEnd = 0;
        [self.imageView.layer addSublayer:layer];
        _progressLayer = layer;
    }
    return _progressLayer;
}

-(UIActivityIndicatorView *)indicator{
    if (!_indicator) {
        UIActivityIndicatorView* indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        indicator.center = CGPointMake(self.width / 2, self.height / 2);
        indicator.hidden = YES;
        [self addSubview:indicator];
    }
    return _indicator;
}

//-(UIView *)contentView{
//    if (!_contentView) {
//        UIView* content = [[UIView alloc]initWithFrame:self.bounds];
//        content.backgroundColor = [UIColor clearColor];
//        [self addSubview:content];
//        _contentView = content;
//    }
//    return _contentView;
//}

-(UIImageView *)imageView{
    if (!_imageView) {
        UIImageView* imv = [[UIImageView alloc]initWithFrame:self.bounds];
        imv.backgroundColor = [UIColor clearColor];
        imv.contentMode = UIViewContentModeScaleToFill;
        [self addSubview:imv];
        _imageView = imv;
    }
    return _imageView;
}

-(void)setContentMode:(UIViewContentMode)contentMode{
    self.imageView.contentMode = contentMode;
}

-(void)setShowTip:(BOOL)showTip{
    _showTip = showTip;
}
-(void)setShowProgress:(BOOL)showProgress{
    _showProgress = showProgress;
}
-(void)setShowIndicator:(BOOL)showIndicator{
    _showIndicator = showIndicator;
}

-(void)setImageURL:(NSURL *)imageURL{
    [self setImageURL:imageURL placeholder:nil];
}
-(void)setImageURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder{
    [self setImageURL:imageURL placeholder:placeholder completion:nil];
}
-(void)setImageURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder completion:(ImageCompletionBlock)completion{
    _imageURL = imageURL;
    __weak typeof(self) _self = self;
    
    self.indicator.hidden = !self.showIndicator;
    
    [CATransaction begin];
    [CATransaction setDisableActions: YES];
    self.progressLayer.hidden = YES;
    self.progressLayer.strokeEnd = 0;
    [CATransaction commit];
    
    [self.imageView setImageWithURL:imageURL placeholder:placeholder options:YYWebImageOptionProgressiveBlur | YYWebImageOptionShowNetworkActivity | YYWebImageOptionSetImageWithFadeAnimation progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        if (expectedSize > 0 && receivedSize > 0) {
            if (_self.showProgress) {
                CGFloat progress = (CGFloat)receivedSize / expectedSize;
                progress = progress < 0 ? 0 : progress > 1 ? 1 : progress;
                if (_self.progressLayer.hidden) _self.progressLayer.hidden = NO;
                _self.progressLayer.strokeEnd = progress;
            }
        }
    } transform:nil completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
        if (stage == YYWebImageStageFinished) {
            _self.progressLayer.hidden = YES;
            [_self.indicator stopAnimating];
            _self.indicator.hidden = YES;
            if (_self.showTip) {
                if (!image) _self.label.hidden = NO;
            }
        }
    }];
    
}


@end
